#!/usr/bin/python
# -*- coding: UTF-8 -*-

import time,threading,sys
sys.path.append("/home/biowin/Minibot/04.RobotSamples/03.SpiderRobot")
from BwRobotLib import BwRobotLib
from SpiderRobot import SpiderRobot
from BwSensorLib import BwSensorLib
import os,inspect

# 加载机器人构型配置
fileName = inspect.getframeinfo(inspect.currentframe()).filename
folderPath     = os.path.dirname(os.path.abspath(fileName))
cfile=folderPath+"/config.txt"


class DanceRobot:
	def __init__(self):
		# 实例化传感器库对象
		self.sensorlib = BwsensorliblibLib("udp")
		# 实例化BwRobotLib库
		self.robotlib = BwRobotLib("udp")
		# 实例化蜘蛛机器人库
		self.spider = SpiderRobot(self.robotlib)
		# 连接机器人设备
		self.robotlib.connectRobot("10.10.100.254",8899) #真机AP模式
        # 导入机器人配置参数
        self.robotlib.loadConfig(config_file)
		#配置ID
		self.spider.bindIds(self.robotlib.module_ids)
		# 时间变量
		self.wait_time = 0.9
		# 蜘蛛机器人运动标志位
		self.flag_threading = 0 
		# 点阵显示
		# 大眼　开心　无表情　
		self.display_data = [[0x36,0x49,0x49,0x00,0x3E],[0x36,0x49,0x49,0x22,0x3E],[0x00,0x00,0x00,0x00,0x00]]


	# 点阵显示表情
	def danceRobotDisplay(self):
		while 1:
			if(self.flag_threading==1):
				self.sensorlib.setMatrixSensor(self.display_data[0]) # 点阵显示大眼表情图案
				time.sleep(self.wait_time)
				self.sensorlib.setMatrixSensor(self.display_data[1]) # 点阵显示开心表情图案
				time.sleep(self.wait_time)
			else:
				self.sensorlib.setMatrixSensor(self.display_data[2]) # 点阵无显示
				time.sleep(self.wait_time)

	# 舞蹈机器人
	def danceRobotMotion(self):
		# 创建线程对象
		self.threading_1 = threading.Thread(target=self.danceRobotDisplay, args=())       # 实例化点阵显示线程	
		# 开启线程
		self.threading_1.start()
		while 1:
			voice = self.sensorlib.readVoiceSensor() #读取声音传感器数据
			print("测量声音值为:%d" % voice) # 输出声音数值
			if (voice > 200):
				print("有声音")
				self.flag_threading = 1
				self.spider.dance() # 蜘蛛机器人跳舞
				self.flag_threading = 0
			else:
				print("没声音")


# 主函数
def main():
    # 实例化舞蹈机器人类
    danceRobot = DanceRobot()
    # 执行舞蹈机器人功能
    danceRobot.danceRobotMotion()


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print(" Program closed! ")
    pass